<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>go[4]-goroutine | Abel&#39;Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="概念go语言中的并发程序通过两种手段来实现。goroutine和channel。顺序通讯进程（communicating sequential processes）简称CSP.并发（concurrency）：逻辑上具备同时处理多个任务的能力。并行（parallelism）：物理上再统一时刻执行多个并发任务。 goroutine简单将goroutine归纳为协程不合适。运行时会创建多个线程来执行并发">
<meta property="og:type" content="article">
<meta property="og:title" content="go[4]-goroutine">
<meta property="og:url" content="http://example.com/2020/11/18/2020/2020-11-18-go[4]-gogrutines/index.html">
<meta property="og:site_name" content="Abel&#39;Blog">
<meta property="og:description" content="概念go语言中的并发程序通过两种手段来实现。goroutine和channel。顺序通讯进程（communicating sequential processes）简称CSP.并发（concurrency）：逻辑上具备同时处理多个任务的能力。并行（parallelism）：物理上再统一时刻执行多个并发任务。 goroutine简单将goroutine归纳为协程不合适。运行时会创建多个线程来执行并发">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-11-17T16:00:00.000Z">
<meta property="article:modified_time" content="2021-07-28T09:13:01.572Z">
<meta property="article:author" content="Abel Sean">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Abel&#39;Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Abel&#39;Blog</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://example.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2020/2020-11-18-go[4]-gogrutines" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/11/18/2020/2020-11-18-go%5B4%5D-gogrutines/" class="article-date">
  <time datetime="2020-11-17T16:00:00.000Z" itemprop="datePublished">2020-11-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      go[4]-goroutine
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><p>go语言中的并发程序通过两种手段来实现。goroutine和channel。顺序通讯进程（communicating sequential processes）简称CSP.<br>并发（concurrency）：逻辑上具备同时处理多个任务的能力。<br>并行（parallelism）：物理上再统一时刻执行多个并发任务。</p>
<h3 id="goroutine"><a href="#goroutine" class="headerlink" title="goroutine"></a>goroutine</h3><p>简单将goroutine归纳为协程不合适。运行时会创建多个线程来执行并发任务，很像多线程和协程的综合体，能最大限度提升执行效率，发挥多核处理能力。<br>go语句，创建一个并发任务单元，放置再系统队列中，等待调度安排系统线程去获取执行权，当前流程不会阻塞，不会等待任务的启动。每个任务单元保存函数指针，参数，还会分配执行的栈内存，相对系统默认的MB级别的栈内存，goroutine栈只有2KB。<br>等待单独的退出事件可以直接使用channel来制作</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    exit := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">struct</span>&#123;&#125;)</span><br><span class="line">    <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">       time.Sleep(time.Second)</span><br><span class="line">       fmt.Println(<span class="string">&quot;goroutine done.&quot;</span>)</span><br><span class="line">       <span class="built_in">close</span>(exit)</span><br><span class="line">    &#125;()</span><br><span class="line">    fmt.Println(<span class="string">&quot;main...&quot;</span>)</span><br><span class="line">    &lt;- exit</span><br><span class="line">    fmt.Println(<span class="string">&quot;main exit.&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果需要等待多个指令可以使用<br>sync.WaitGroup来处理。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> wg sync.WaitGroup</span><br><span class="line">wg.Add(<span class="number">1</span>)</span><br><span class="line">wg.Done()</span><br><span class="line">wg.Wait()</span><br></pre></td></tr></table></figure>
<p>一些有用的函数<br>runtime.NumCPU<br>查询服务器的cpu个数<br>runtime.GOMAXPROCS<br>参数小于1，表示查询当前设置的值，否则就是设置参与并发的线程数。<br>runtime.Gosched<br>暂停，释放线程去执行其他的任务，当前线程被放回队列，等待下次调度是恢复。<br>runtime.Goexit<br>在goroutine里面执行这个，将会终端任务，无论身处在哪一层，Goexit都能立即终止整个调用堆栈，这个和return退出当前函数不一样。但是不要在main函数里面调用这个函数,否则会直接panic。</p>
<h3 id="channel"><a href="#channel" class="headerlink" title="channel"></a>channel</h3><p>通道是用于连接两个不同的线程。分为同步和异步的两种通道。<br>如果通道的长度为0，就是同步通道，就是需要等待处理方开始处理之后，才会执行后续操作。<br>如果通道长度&gt;0，则是异步通道，投递了数据之后就能直接走了。<br>这个例子就是演示同步方式的通道，使用for来获取管道中的内容。</p>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    done := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">struct</span> &#123;&#125;)</span><br><span class="line">    c := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">    <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">defer</span> <span class="built_in">close</span>(done)</span><br><span class="line">        <span class="keyword">for</span> x:=<span class="keyword">range</span> c&#123;</span><br><span class="line">             fmt.Println(x)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;()</span><br><span class="line">    c &lt;- <span class="number">1</span></span><br><span class="line">    c &lt;- <span class="number">2</span></span><br><span class="line">    c &lt;<span class="number">-3</span></span><br><span class="line">    <span class="built_in">close</span>(c)</span><br><span class="line">    &lt;-done</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通道默认是双向的。如果特殊情况下需要将通道的单向端获取出来，赋值给某个函数，控制其行为，只能单向，那就可以参考下面的代码</p>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">      <span class="keyword">var</span> wg sync.WaitGroup</span><br><span class="line">      wg.Add(<span class="number">2</span>)</span><br><span class="line">      c := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">      <span class="keyword">var</span> send <span class="keyword">chan</span> &lt;- <span class="keyword">int</span> = c</span><br><span class="line">      <span class="keyword">var</span> recv &lt;- <span class="keyword">chan</span> = c</span><br><span class="line">      <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">          <span class="keyword">defer</span> wg.Done()</span><br><span class="line">          <span class="keyword">for</span> x := <span class="keyword">range</span> recv &#123;</span><br><span class="line">              <span class="built_in">println</span>(x)</span><br><span class="line">          &#125;</span><br><span class="line">     &#125;()</span><br><span class="line">     <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">          <span class="keyword">defer</span> wg.Done()</span><br><span class="line">          <span class="keyword">for</span> i:=<span class="number">0</span>;i&lt;<span class="number">3</span>;i++ &#123;</span><br><span class="line">               send &lt;-I</span><br><span class="line">         &#125;</span><br><span class="line">   &#125;()</span><br><span class="line">   wg.Wait()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样就能把通道的单向通道赋值出来，  &lt;-send或者 recv &lt;- 1，语句就无法执行。<br>如果一个goroutine中要同时处理多个通道，可以选用select语句。它会随机选择一个可用通道收发操作。找一段leaf的源码来参考</p>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 构造一个有缓冲区的chan</span></span><br><span class="line">...</span><br><span class="line"><span class="keyword">var</span> ChanCall  <span class="keyword">chan</span> *CallInfo</span><br><span class="line">...</span><br><span class="line">ChanCall = <span class="built_in">make</span>(<span class="keyword">chan</span> *CallInfo, <span class="number">1000</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(s *Skeleton)</span> <span class="title">Run</span><span class="params">(closeSig <span class="keyword">chan</span> <span class="keyword">bool</span>)</span></span> &#123;</span><br><span class="line">	<span class="keyword">for</span> &#123;</span><br><span class="line">		<span class="keyword">select</span> &#123;</span><br><span class="line">		<span class="keyword">case</span> &lt;-closeSig:</span><br><span class="line">			s.commandServer.Close()</span><br><span class="line">			s.server.Close()</span><br><span class="line">			<span class="keyword">for</span> !s.g.Idle() || !s.client.Idle() &#123;</span><br><span class="line">				s.g.Close()</span><br><span class="line">				s.client.Close()</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		<span class="keyword">case</span> ri := &lt;-s.client.ChanAsynRet:</span><br><span class="line">			s.client.Cb(ri)</span><br><span class="line">		<span class="keyword">case</span> ci := &lt;-s.server.ChanCall:</span><br><span class="line">			s.server.Exec(ci)</span><br><span class="line">		<span class="keyword">case</span> ci := &lt;-s.commandServer.ChanCall:</span><br><span class="line">			s.commandServer.Exec(ci)</span><br><span class="line">		<span class="keyword">case</span> cb := &lt;-s.g.ChanCb:</span><br><span class="line">			s.g.Cb(cb)</span><br><span class="line">		<span class="keyword">case</span> t := &lt;-s.dispatcher.ChanTimer:</span><br><span class="line">			t.Cb()</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://example.com/2020/11/18/2020/2020-11-18-go[4]-gogrutines/" data-id="ckrn3an76000x20xw8ru3br18" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/golang/" rel="tag">golang</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/11/18/2020/2020-11-18-go%5B3%5D-%E6%8E%A5%E5%8F%A3/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          go[3]-接口
        
      </div>
    </a>
  
  
    <a href="/2020/11/18/2020/2020-11-18-go%5B5%5D-%E6%B5%8B%E8%AF%95/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">go[4]-测试</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/3D/" rel="tag">3D</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/AI/" rel="tag">AI</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/C/" rel="tag">C++</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Game/" rel="tag">Game</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Go/" rel="tag">Go</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Linux/" rel="tag">Linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Math/" rel="tag">Math</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Server/" rel="tag">Server</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Unreal-Engine4/" rel="tag">Unreal Engine4</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/" rel="tag">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/golang/" rel="tag">golang</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/guitar/" rel="tag">guitar</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/node-js/" rel="tag">node.js</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/protobuf/" rel="tag">protobuf</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/recast/" rel="tag">recast</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/redis/" rel="tag">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/type/" rel="tag">type</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/vscode/" rel="tag">vscode</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%BF%90%E7%BB%B4/" rel="tag">运维</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/3D/" style="font-size: 10px;">3D</a> <a href="/tags/AI/" style="font-size: 11.67px;">AI</a> <a href="/tags/C/" style="font-size: 15px;">C++</a> <a href="/tags/Game/" style="font-size: 18.33px;">Game</a> <a href="/tags/Go/" style="font-size: 13.33px;">Go</a> <a href="/tags/Linux/" style="font-size: 13.33px;">Linux</a> <a href="/tags/Math/" style="font-size: 11.67px;">Math</a> <a href="/tags/Server/" style="font-size: 16.67px;">Server</a> <a href="/tags/Unreal-Engine4/" style="font-size: 10px;">Unreal Engine4</a> <a href="/tags/git/" style="font-size: 10px;">git</a> <a href="/tags/golang/" style="font-size: 20px;">golang</a> <a href="/tags/guitar/" style="font-size: 10px;">guitar</a> <a href="/tags/node-js/" style="font-size: 10px;">node.js</a> <a href="/tags/protobuf/" style="font-size: 10px;">protobuf</a> <a href="/tags/python/" style="font-size: 10px;">python</a> <a href="/tags/recast/" style="font-size: 11.67px;">recast</a> <a href="/tags/redis/" style="font-size: 10px;">redis</a> <a href="/tags/type/" style="font-size: 10px;">type</a> <a href="/tags/vscode/" style="font-size: 10px;">vscode</a> <a href="/tags/%E8%BF%90%E7%BB%B4/" style="font-size: 16.67px;">运维</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">June 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">April 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">March 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/01/">January 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/12/">December 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/11/">November 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">March 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">November 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/19/2021/2021-07-19-etcd-learn/">go-etcd阅读笔记</a>
          </li>
        
          <li>
            <a href="/2021/07/19/2021/2021-07-19-socketop-learn/">REUSEPORT-REUSEADDR-学习</a>
          </li>
        
          <li>
            <a href="/2021/06/22/2021/2021-06-22-go-ethereum-learn/">go-ethereum阅读笔记</a>
          </li>
        
          <li>
            <a href="/2021/06/21/2021/2021-06-21-server%E6%B5%8B%E8%AF%95%E5%B7%A5%E5%85%B7/">server测试工具</a>
          </li>
        
          <li>
            <a href="/2021/06/09/2021/2021-06-09-pprof-doc/">go-pprof</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2021 Abel Sean<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>